import 'dart:collection';

import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';

import 'package:novel_reader/model/book.dart';
import 'package:novel_reader/model/chapter.dart';
import 'package:novel_reader/utils/hive_storage.dart';
import 'package:novel_reader/utils/http_util.dart';

class FishHawkApi {
  static String? getType(String? code) {
    if (null == code || code.length < 4) {
      return null;
    }
    if (code[0] == 'n') {
      return 'syosetu';
    } else if (code.indexOf('/') > 0) {
      return code.split('/')[0];
    }
    return 'kakuyomu';
  }

  static String? getRealCode(String? code) {
    if (null != code && code.indexOf('/') > 0) {
      return code.split('/')[1];
    }
    return code;
  }

  static String formatDate(String? dateStr, DateFormat sdf) {
    int len;
    if (null == dateStr || (len = dateStr.length) == 0) {
      return '';
    }
    if (len < 12) {
      return sdf.format(
        DateTime.fromMillisecondsSinceEpoch(int.parse(dateStr) * 1000),
      );
    }
    return sdf.format(DateTime.fromMillisecondsSinceEpoch(int.parse(dateStr)));
  }

  static Future<void> initBook(Book? book) async {
    String? type = getType(book?.code);
    if (null == book || null == type) {
      return;
    }
    var result = await HttpUtil.get(
      url:
          'https://books.fishhawk.top/api/novel/$type/${getRealCode(book.code)}',
    );
    var json = result.data;
    book.wenkuId = json['wenkuId'];
    book.name = json['titleZh'];
    book.titleJp = json['titleJp'];
    if (null == book.name || book.name!.isEmpty) {
      book.name = book.titleJp;
    }
    try {
      book.author = json['authors'].join('、');
    } catch (e) {
      //
    }
    book.introductionJp = json['introductionJp'];
    book.introduction = json['introductionZh'];
    List arr = json['toc'];
    String? chapterGroup;
    String? chapterGroupJp;
    DateFormat sdf = DateFormat('yyyy-MM-dd HH:mm');
    LinkedHashMap<String, Chapter> chapters = LinkedHashMap();
    int order = 0;
    for (var item in arr) {
      String? titleZh = item['titleZh'];
      String? titleJp = item['titleJp'];
      titleZh ??= titleJp;
      if (!item.containsKey('chapterId')) {
        chapterGroup = titleZh;
        chapterGroupJp = titleJp;
      } else {
        if (null != chapterGroup) {
          titleZh = '$chapterGroup $titleZh';
          titleJp = '$chapterGroupJp $titleJp';
        }
        String? chapterId = '${item['chapterId']}';
        chapters[chapterId] = Chapter(
          bookCode: book.code,
          chapterId: chapterId,
          title: titleZh,
          titleJp: titleJp,
          update: formatDate('${item['createAt']}', sdf),
          order: order++,
        );
      }
    }
    List<Chapter> bookChapters = HiveStorage.getChaptersByBookCode(book.code);
    if (bookChapters.isNotEmpty) {
      for (Chapter chapter in bookChapters) {
        Chapter? c = chapters[chapter.chapterId];
        if (null == c) {
          chapters[chapter.chapterId] = chapter;
        } else {
          c.content = chapter.content;
          c.translation = chapter.translation;
        }
      }
    }
    if (book.initTime == null || book.initTime! < 1) {
      book.initTime = DateTime.now().millisecondsSinceEpoch;
    }
    HiveStorage.replaceChaptersForBook(book.code, chapters.values.toList());
  }

  static String? arr2Str(List<dynamic>? arr) {
    return arr?.join('\n');
  }

  static Future<bool> initChapter(Chapter? chapter) async {
    String? type = getType(chapter?.bookCode);
    if (null == type) {
      return false;
    }
    var response = await HttpUtil.get(
      url:
          'https://books.fishhawk.top/api/novel/$type/${getRealCode(chapter?.bookCode)}/chapter/${chapter!.chapterId}',
    );
    Map? json = response.data;
    if (json == null) {
      return false;
    }
    List<dynamic>? arr;
    if (json.containsKey('sakuraParagraphs')) {
      arr = json['sakuraParagraphs'];
    } else if (json.containsKey('gptParagraphs')) {
      arr = json['gptParagraphs'];
    } else if (json.containsKey('baiduParagraphs')) {
      arr = json['baiduParagraphs'];
    } else if (json.containsKey('youdaoParagraphs')) {
      arr = json['youdaoParagraphs'];
    }
    if (null != arr && arr.isNotEmpty) {
      chapter.translation = arr2Str(arr);
    }
    chapter.content = arr2Str(json['paragraphs']);
    return true;
  }
}
